package dao

import javax.inject.Inject
import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.{JdbcProfile, JdbcType, PostgresProfile}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * Created by yz on 2018/5/29
 */
class GroupFileDataDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import utils.MyPostgresProfile.api._

  type MyRow = GroupFileDataRow
  val table = GroupFileData

  def selectAllFileName(userId: Int) = db.run(table.
    filter(x => x.userId === userId).map(_.fileName).result.map(_.toList))

  def insert(row: MyRow): Future[Unit] = db.run(table += row).map(_ => ())

  def selectAll(userId: Int) = db.run(table.
    filter(x => x.userId === userId).sortBy(_.id.desc).result)

  def selectAll(userId: Int, samples: List[String]) = db.run(table.
    filter(x => x.userId === userId).filter { x =>
    (samples.bind) <@: (x.groupInfo.akeys)
  }.sortBy(_.id.desc).result)

  def selectAllOnlyInter(userId: Int, samples: List[String]) = db.run(table.
    filter(x => x.userId === userId).filter { x =>
    (x.groupInfo).?|(samples.bind)
  }.sortBy(_.id.desc).result)

  def selectAllTest(userId: Int, samples: List[String]) = db.run(table.
    filter(x => x.userId === userId).filter { x =>
    (x.groupInfo).?|(samples.bind)
  }.map { x =>
    x.groupInfo.akeys
  }.result)

  def selectAll(userId: Int, samples: List[String], groupNum: Int) = db.run(table.
    filter(x => x.userId === userId).filter { x =>
    (samples.bind) <@: (x.groupInfo.akeys)
  }.filter { x =>
    x.groupInfo.slice(samples.bind).avals.arrayDistinct.length() === groupNum.bind
  }.result)

  def selectAllMul(userId: Int, samples: List[String]) = db.run(table.
    filter(x => x.userId === userId).filter { x =>
    (samples.bind) <@: (x.groupInfo.akeys)
  }.filter { x =>
    x.groupInfo.slice(samples.bind).avals.arrayDistinct.length() > 2.bind
  }.result)

  def select(userId: Int, fileName: String) = db.run(table.
    filter(x => x.userId === userId).filter(_.fileName === fileName).result.head)

  def select(id: Int) = db.run(table.
    filter(x => x.id === id).result.head)

  def selectAll(ids: List[Int]) = db.run(table.
    filter(x => x.id.inSetBind(ids)).result)

  def delete(userId: Int, id: Int): Future[Unit] = db.run(table.filter(_.userId === userId).filter(_.id === id).
    delete).map(_ => ())

  def deletes(userId: Int, ids: List[Int]): Future[Unit] = db.run(table.filter(_.userId === userId).
    filter(_.id.inSetBind(ids)).delete).map(_ => ())

  def update(row: MyRow): Future[Unit] = db.run(table.filter(_.id === row.id).update(row)).
    map(_ => ())


}
